import uuid
from datetime import datetime
# from motor.motor_asyncio import AsyncIOMotorClient
from loguru import logger


import pymongo


class MongDb:
    def __init__(self):
        self.con = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
        self.db = self.con["personal_gain"]

    def create_conn(self, collection: str, idxname):
        """
        创建集合
        :param collection: 集合名
        :param idxname: 索引
        :return:
        """
        coltion = self.db[collection]
        if isinstance(idxname, str):
            coltion.create_index(idxname)
        elif isinstance(idxname, list):
            coltion.create_index([(na, 1) for na in idxname])
        return coltion

    def in_data(self, collection, data: dict):
        uid = None
        try:
            if data.get('_id'):
                uid = data['_id']
                udt = data.copy()
                del udt['_id']
                udt.update({"updtime": datetime.now()})
                collection.update_one({"_id": uid}, {"$set": udt})
            else:
                uid = uuid.uuid1().hex
                now = datetime.now()
                # print("data",data)
                data.update({"_id": uid, "addtime": now, "updtime": now})
                # print('updata',data)
                collection.insert_one(data)
        except Exception as e:
            logger.error(f"插入数据时出错了！{e}")
        finally:
            return uid
